package com.yiyuan.app.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.net.Socket;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Slf4j
public class TcpUtils {
    private static final ConcurrentHashMap<String, Socket> clientMap = new ConcurrentHashMap<>();

    /**
     * 保存tcp通信链接
     *
     * @param deviceNo
     * @param socket
     */
    public static void addSocket(String deviceNo, Socket socket) {
        clientMap.put(deviceNo, socket);
        log.info("添加设备通道成功：clientMap={}", clientMap);
    }


    public static void sendMessage(Socket socket, String message) throws IOException {
        if (!clientIsClose(socket)) {
            String[] split = message.split(" ");
            byte[] bytes = new byte[split.length];
            for (int i = 0; i < split.length; i++) {
                bytes[i] = (byte) Integer.parseInt(split[i], 16);
            }
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(bytes);
            outputStream.flush();
            log.info("发送街机爆爆机消息成功：command={}", message);
        }
    }

    /**
     * 判断链接是否关闭，返回true则关闭，返回false没关闭
     *
     * @param socket
     * @return
     */
    public static Boolean clientIsClose(Socket socket) {
        try {
            socket.sendUrgentData(0xFF);
            return Boolean.FALSE;
        } catch (Exception e) {
            return Boolean.TRUE;
        }
    }

    /**
     * 删除tcp通信链接
     *
     * @param deviceNo
     */
    public static void delSocket(String deviceNo) {
        clientMap.remove(deviceNo);
    }

    /**
     * 判断链接是否保存下来
     *
     * @param socket
     * @return
     */
    public static Boolean isContainSocket(Socket socket) {
        return clientMap.containsValue(socket);
    }

    /**
     * 获取设备对应的链接
     *
     * @param deviceNo
     * @return
     */
    public static Socket findSocket(String deviceNo) {
        Socket socket = clientMap.get(deviceNo);
        if (Objects.isNull(socket)) {
            log.error("设备{}连接不存在", deviceNo);
        }
        return socket;
    }


//    /**
//     * 获取设备对应的链接
//     *
//     * @param socket
//     * @return
//     */
//    public static String findDeviceNo(Socket socket) {
//        return clientMap.entrySet().stream().filter(kvEntry -> Objects.equals(kvEntry.getValue(), socket)).map(Map.Entry::getKey).collect(Collectors.toList()).get(0);
//    }
}
